import {map, isEmpty, filter, find, clone, isString, get} from 'lodash'
import {mapGetters, mapState, mapActions} from 'vuex'

const mixin = {
  props: ['asset'],
  methods: {
    back(){
      this.$emit('toggleModel', 'view')
    },
    save() {
      let needRefreshAssetMeta = this._hasNewPivot()
      return this.validate().then(() => {
        this.$loading('保存中...')
        return this.store(this.data).then(response => {
          let savedAsset = response.data.asset || response.data.assetStock || response.data.assetBundle
          this.$loading.close()
          // merge new data for table grid
          if (needRefreshAssetMeta.length > 0) {
            let promises = map(needRefreshAssetMeta, name =>
                this.fetchAssetMeta({ name })
            )
            Promise.all(promises).then(() => {
              this.original = Object.assign(this.original, savedAsset)
              this.data = Object.assign(this.data, savedAsset)
            })
          } else {
            this.original = Object.assign(this.original, savedAsset)
            this.data = Object.assign(this.data, savedAsset)
          }
          this.$msgBox('保存成功')
        }).catch((error: any) => {
          this.$loading.close()
          this.$msgBox('保存失败')
          return Promise.reject()
        })
      })
    },
    reset() {
      this.data = Object.assign({}, this.original)
    },
    validate() {
      return new Promise((resolve, reject) => {
        this.$refs.form.validate() ? resolve() : reject()
      })
    },
    isNew(name) {
      if (isEmpty(get(this.data, name))) {
        return ''
      }
      return get(this.data, `${name}_id`) == null ? '新增' : ''
    },
    _hasNewPivot() {
      let pivotList = ['brand', 'affiliation', 'vendor', 'keeper', 'location']
      return _.filter(pivotList, name => {
        let pivot = this.data[name]
        return !isEmpty(pivot) && isString(pivot)
      })
    },
    syncPivotId(name) {
      let pivot = this.data[name]
      let id = isString(pivot) ? null : get(pivot, 'id', null)
      this.data[`${name}_id`] = id
    },
    syncMandatoryPivot(name) {
      let pivot = this.data[name]
      if (isString(pivot)) {
        this.data[name] = null
        this.$refs[name].clearableCallback()
        return
      }
      this.data[`${name}_id`] = get(pivot, 'id', null)
    }
  },
  computed: {
    ...mapState('asset', [
      'assetStatus',
      'assetCategories',
      'assetBrands',
      'assetAffiliations',
      'assetVendors',
      'assetKeepers',
      'assetLocations'
    ]),
    ...mapGetters('asset', ['primaryCategories']),
    subCategories(): any {
      if (isEmpty(this.data.category)) {
        return []
      }
      let primaryCategoryId = this.data.category.id
      return filter(
          this.assetCategories,
          x => x.parent_id === primaryCategoryId
      )
    }
  },
  watch: {
    asset: {
      handler(val) {
        this.original = val
        this.data = clone(val)
        setTimeout(() => {
          this.validate()
        }, 200)
      },
      immediate: true
    },
    'data.category': function (val) {
      // 主类已经改变
      let parentId = get(this.data, 'sub_category.parent_id', 'N/A')
      if (val == null || parentId !== val.id) {
        this.data.sub_category = null
        this.data.sub_category_id = null
        this.$refs.sub_category.clearableCallback()
      }
    },
    data: {
      handler() {
        let isChanged =
            JSON.stringify(this.original) !== JSON.stringify(this.data)
        if (isChanged) {
          this.$emit('dirty')
        }
      },
      deep: true
    }
  },
  data() {
    return {
      rules: {
        required: (value: any) => !!value || '必填'
      },
      data: {},
      original: {},
      datePick: false
    }
  }
}

export default mixin